package com.pll.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisTemplateConfig
 * @Description TODO
 * @Author 小鹿
 * @Date 2025/5/21 11:05
 */
@Configuration
public class RedisTemplateConfig
{
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        //创建redisTemplate对象，并设置连接方式
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        //构建序列化对象,将数据可以转换成String类型
        FastJsonRedisSerializer<String> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(String.class);

        //进行序列化 ==》 key和value都需要序列化，String类型，也可以避免中文无法显示的问题
        //设置key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置value序列化
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);

        //进行序列化 ==》 list、set、hash等
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        //设置redis支持事务
        redisTemplate.setEnableDefaultSerializer(true);

        //让配置生效
        redisTemplate.afterPropertiesSet();

        //让配置生效
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}